import React, { useState } from 'react';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import {
  makeStyles,
  Avatar,
  Button,
  CssBaseline,
  TextField,
  FormControlLabel,
  Checkbox,
  Link,
  Grid,
  Typography,
  Snackbar,
  Container,
} from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { login } from '../../store/actions';
import { signIn } from '../../api/actions/user';

const useStyles = makeStyles((theme) => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));

function SignIn(props) {
  const { userLogin } = props;
  const classes = useStyles();
  const history = useHistory();

  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');

  const [hasError, setHasError] = useState(false);

  const handleSignIn = async () => {
    const res = await signIn({ phone, password });
    if (res.code === 0) {
      const userInfo = {
        token: res.data.token,
        ...res.data.userInfo,
      };
      window.localStorage.setItem('userInfo', JSON.stringify(userInfo));
      userLogin(userInfo);
      history.push('/');
    } else {
      setHasError(res.message);
    }
  };

  const handleCloseSnackbar = () => {
    setHasError(false);
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />

      <Snackbar
        open={Boolean(hasError)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        onClose={handleCloseSnackbar}
      >
        <Alert variant="outlined" severity="error">
          {hasError}
        </Alert>
      </Snackbar>

      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          登陆
        </Typography>
        <div className={classes.form} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="phone"
            label="手机"
            name="phone"
            autoComplete="phone"
            autoFocus
            onChange={(e) => { setPhone(e.target.value); }}
            value={phone}
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="密码"
            type="password"
            id="password"
            autoComplete="current-password"
            onChange={(e) => { setPassword(e.target.value); }}
            value={password}
          />
          <FormControlLabel
            control={<Checkbox value="remember" color="primary" />}
            label="记住我"
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={handleSignIn}
          >
            登陆
          </Button>
          <Grid container>
            <Grid item xs>
              <Link href="#" variant="body2">
                忘记密码?
              </Link>
            </Grid>
            <Grid item>
              <Link href="/signUp" variant="body2">
                没有账号?去注册
              </Link>
            </Grid>
          </Grid>
        </div>
      </div>
    </Container>
  );
}

const mapDispatchToProps = (dispatch) => ({
  userLogin: (userInfo) => dispatch(login(userInfo)),
});

export default connect(
  null,
  mapDispatchToProps,
)(SignIn);
